package com.zzyl.nursing.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.LocalDateTimeUtil;
import cn.hutool.core.text.CharSequenceUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zzyl.common.constant.CacheConstants;
import com.zzyl.nursing.domain.AlertData;
import com.zzyl.nursing.domain.AlertRule;
import com.zzyl.nursing.domain.DeviceData;
import com.zzyl.nursing.mapper.AlertRuleMapper;
import com.zzyl.nursing.mapper.DeviceMapper;
import com.zzyl.nursing.service.IAlertDataService;
import com.zzyl.nursing.service.IAlertRuleService;
import com.zzyl.system.mapper.SysUserRoleMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.temporal.ChronoUnit;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * 报警规则Service业务层处理
 * 
 * @author alexis
 * @date 2025-06-09
 */
@Service
public class AlertRuleServiceImpl extends ServiceImpl<AlertRuleMapper, AlertRule> implements IAlertRuleService
{
    @Autowired
    private AlertRuleMapper alertRuleMapper;
    @Autowired
    private RedisTemplate<String, String> redisTemplate;
    @Autowired
    private DeviceMapper deviceMapper;
    @Autowired
    private SysUserRoleMapper sysUserRoleMapper;
    @Autowired
    private IAlertDataService  alertDataService;
    /**
     * 查询报警规则
     * 
     * @param id 报警规则主键
     * @return 报警规则
     */
    @Override
    public AlertRule selectAlertRuleById(Long id)
    {
        return alertRuleMapper.selectById(id);
    }

    /**
     * 查询报警规则列表
     * 
     * @param alertRule 报警规则
     * @return 报警规则
     */
    @Override
    public List<AlertRule> selectAlertRuleList(AlertRule alertRule)
    {
        return alertRuleMapper.selectAlertRuleList(alertRule);
    }

    /**
     * 新增报警规则
     * 
     * @param alertRule 报警规则
     * @return 结果
     */
    @Override
    public int insertAlertRule(AlertRule alertRule)
    {
        return alertRuleMapper.insert(alertRule);
    }

    /**
     * 修改报警规则
     * 
     * @param alertRule 报警规则
     * @return 结果
     */
    @Override
    public int updateAlertRule(AlertRule alertRule)
    {
        return alertRuleMapper.updateById(alertRule);
    }

    /**
     * 批量删除报警规则
     * 
     * @param ids 需要删除的报警规则主键
     * @return 结果
     */
    @Override
    public int deleteAlertRuleByIds(Long[] ids)
    {
        return alertRuleMapper.deleteBatchIds(Arrays.asList(ids));
    }

    /**
     * 删除报警规则信息
     * 
     * @param id 报警规则主键
     * @return 结果
     */
    @Override
    public int deleteAlertRuleById(Long id)
    {
        return alertRuleMapper.deleteById(id);
    }

    @Override
    public void alertFilter() {
        //判断当前是否有报警规则
        Long count = lambdaQuery().eq(AlertRule::getAlertDataType, 0)
                .count();
        if (count == 0L){
            return;
        }
        //获取设备最新数据
        List<Object> values = redisTemplate.opsForHash().values(CacheConstants.IOT_DEVICE_LAST_DATA);
        if (CollUtil.isEmpty(values)){
            return;
        }
        List<DeviceData> deviceDataList = new ArrayList<>();
        values.forEach(value -> {
            List<DeviceData> deviceDatas = JSONUtil.toList(value.toString(), DeviceData.class);
            deviceDataList.addAll(deviceDatas);
        });

        deviceDataList.forEach(this::alertFilter);
    }

    private void alertFilter(DeviceData deviceData) {
        //校验时间是否超过60秒
        LocalDateTime alarmTime = deviceData.getAlarmTime();
        long between = LocalDateTimeUtil.between(alarmTime, LocalDateTime.now(), ChronoUnit.SECONDS);
        if (between > 60){
            return;
        }
        //查询所有的该产品规则和该物模型的规则
        List<AlertRule> allRules = lambdaQuery()
                .eq(AlertRule::getProductKey, deviceData.getProductKey())
                .eq(AlertRule::getFunctionId, deviceData.getFunctionId())
                .eq(AlertRule::getIotId, -1)
                .eq(AlertRule::getStatus, 1)
                .list();

        //查询所有的该产品规则和指定某一条数据的规则
        List<AlertRule> iotRules = lambdaQuery()
                .eq(AlertRule::getProductKey, deviceData.getProductKey())
                .eq(AlertRule::getFunctionId, deviceData.getFunctionId())
                .eq(AlertRule::getIotId, deviceData.getIotId())
                .eq(AlertRule::getStatus, 1)
                .list();
        //将allRules和iotRules进行合并去重
        Collection<AlertRule> alertRulesList = CollUtil.addAll(allRules, iotRules);
        if (CollUtil.isEmpty(alertRulesList)){
            return;
        }
        ArrayList<AlertRule> alertRules = CollUtil.distinct(alertRulesList);
        alertRules.forEach(alertRule -> deviceDataAlarmHandler(alertRule, deviceData));
    }

    private void deviceDataAlarmHandler(AlertRule alertRule, DeviceData deviceData) {
        //第一层校验：判断生效时间
        //获取上报时间
        String iotId = deviceData.getIotId();
        LocalDateTime alarmDateTime = deviceData.getAlarmTime();
        LocalTime alarmTime = alarmDateTime.toLocalTime();
        //获取报警时间段
        String alertEffectivePeriod = alertRule.getAlertEffectivePeriod();
        List<String> split = StrUtil.split(alertEffectivePeriod, "~");
        if (CollUtil.isEmpty(split) || split.size() != 2){
            return;
        }
        //将报警时间段转换成LocalTime
        LocalTime startTime = LocalTime.parse(split.get(0));
        LocalTime endTime = LocalTime.parse(split.get(1));
        //判断上报时间是否在报警时间段内
        if ((alarmTime.isBefore(startTime) || alarmTime.isAfter(endTime))){
            return;
        }
        //第二层校验：判断阈值
        //获取阈值
        String countKey = CacheConstants.ALERT_TRIGGER_COUNT_PREFIX + ":" + deviceData.getIotId() + ":" + deviceData.getFunctionId() + ":" + alertRule.getId();
        Double value = alertRule.getValue();
        String operator = alertRule.getOperator();
        String dataValue = deviceData.getDataValue();
        int compare = Double.compare(Double.parseDouble(dataValue), value);
        if ((">=".equals(operator) && compare < 0) || ("<".equals(operator) && compare >= 0)){
            //清空redis中的报警次数
            redisTemplate.delete(countKey);
            return;
        }
        //第三层校验：判断沉默周期
        String silentKey = CacheConstants.ALERT_SILENT_PREFIX + ":" + deviceData.getIotId() + ":" + deviceData.getFunctionId() + ":" + alertRule.getId();
        String silent = redisTemplate.opsForValue().get(silentKey);
        if (StrUtil.isNotEmpty(silent)){
            return;
        }
        //第四层校验：判断持续周期
        String count = redisTemplate.opsForValue().get(countKey);
        Integer countValue = StrUtil.isEmpty(count) ? 1 : Integer.parseInt(count) + 1;
        if (!countValue.equals(alertRule.getDuration())){
            redisTemplate.opsForValue().set(countKey, String.valueOf(countValue));
            return;
        }
        redisTemplate.delete(countKey);
        redisTemplate.opsForValue().set(silentKey, "1", alertRule.getAlertSilentPeriod(), TimeUnit.MINUTES);
        List<Long> usetId;
        if (alertRule.getAlertDataType().equals(0)){
            //老人异常数据
            if (deviceData.getLocationType().equals(0)){
                //随身设备异常
                usetId = deviceMapper.selectNursingIdsByIotIdWithElder(iotId);
            }else {
                //固定设备异常
                usetId = deviceMapper.selectNursingIdsByIotIdWithBed(iotId);
            }
        }else {
            //设备异常数据
            usetId = sysUserRoleMapper.selectUserIdByRoleName("维修工");
        }
        List<Long> managerIds = sysUserRoleMapper.selectUserIdByRoleName("超级管理员");
        Collection<Long> UserIds = CollUtil.addAll(usetId, managerIds);
        List<Long> distinctUserIds = CollUtil.distinct(UserIds);
        insertAlertData(alertRule, distinctUserIds, deviceData);
    }

    private void insertAlertData(AlertRule alertRule, List<Long> distinctUserIds, DeviceData deviceData) {
        List<AlertData> alertDataList = new ArrayList<>();
        distinctUserIds.forEach(userId -> {
            AlertData alertData = BeanUtil.toBean(deviceData, AlertData.class);
            alertData.setUserId(userId);
            alertData.setId(null);
            alertData.setAlertRuleId(alertRule.getId());
            String alertReason  = CharSequenceUtil.format("{}{}{},持续{}个周期就报警", alertRule.getFunctionName(), alertRule.getOperator(), alertRule.getValue(), alertRule.getDuration());
            alertData.setAlertReason(alertReason);
            alertData.setType(alertRule.getAlertDataType());
            alertData.setStatus(0);
            alertDataList.add(alertData);
        });
        alertDataService.saveBatch(alertDataList);
    }
}
